package software.lib.service;

import software.lib.dao.UserDao;
import software.lib.entity.User;
import software.lib.exception.NoSuchEntityException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by Wang on 2017/5/3.
 */
@Service
@Transactional
public class UserService {
    @Autowired
    private UserDao userDao;

    @Transactional(readOnly = true)
    public User verify(User user){
        if(StringUtils.isBlank(user.getLoginName())){
            throw new IllegalArgumentException("用户登陆名称不可为空！");
        }
        User u = userDao.findByLoginName(user.getLoginName());
        if(u==null){
            throw new NoSuchEntityException("该用户不存在！");
        }
        if(StringUtils.equals(user.getLoginPassword(),u.getLoginPassword())){
            return u;
        }
        return null;
    }



    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void modifyUser(User u) {
        userDao.update(u);
    }

    public User regist(User user) {
        if(StringUtils.isBlank(user.getLoginName())){
            throw new IllegalArgumentException("用户登陆名称不可为空！");
        }

        if(StringUtils.isBlank(user.getIdCard())){
            throw new IllegalArgumentException("身份证号码不可为空！");
        }

        User u = userDao.findByLoginName(user.getLoginName());
        if(u!=null){
            throw new DuplicateKeyException("该用户名已被占用！");
        }
        u = userDao.findById(user.getIdCard());
        if(u!=null){
            throw new DuplicateKeyException("该身份证号码已被注册！");
        }

        String idCard = user.getIdCard();
        char sex = idCard.charAt(16);

        user.setSex((sex-'0')%2!=0);

        userDao.add(user);
        return user;
    }

    public boolean deleteUser(User user) {
        User u = userDao.findById(user.getIdCard());
        if(u==null){
            throw new NoSuchEntityException("该用户不存在！");
        }else{
            userDao.delete(u);
        }
        return true;
    }
}
